#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "MULT.h"
#include "PF_UTIL.h"
#include "simparameters.h"


//The m x m multiplier for the freactions.

FPOINT_PTR MULT(FPOINT *Mx, FPOINT *My) {
    int i,j;
    char *MxFraMult=(char *)malloc(sizeof(char)*(FRACTION_WIDTH+2));
    char *MyFraMult=(char *)malloc(sizeof(char)*(FRACTION_WIDTH+2));
    char * mult_res;
    char pre_Norm[FRACTION_WIDTH+4];
    char *post_Norm;
    char sign_out;
    int MxEx_int=binary2INT(Mx->Exponent,EXPONENT_WIDTH);;
    int MxEy_int=binary2INT(My->Exponent,EXPONENT_WIDTH);;
    int bias_base=pow(2,EXPONENT_WIDTH-1);
    int out_exponent_int;

    //First of all, get the sign first
    if(Mx->sign==My->sign){
        sign_out='0';
    }else{
        sign_out='1';
    }

    //Update the exponent in INT form first, might need to be updated later on
    out_exponent_int=MxEx_int+MxEy_int-bias_base;


    //Do the multiplication for the fractions.
    MxFraMult[0]='1';
    MyFraMult[0]='1';
    for(i=1;i<FRACTION_WIDTH+2;i++){
        MxFraMult[i]=Mx->Fraction[i-1];
        MyFraMult[i]=My->Fraction[i-1];
    }

    mult_res=MbyMMulttplier(MxFraMult,MyFraMult,FRACTION_WIDTH+1);
    strncpy (pre_Norm,mult_res,FRACTION_WIDTH+3);
    pre_Norm[FRACTION_WIDTH+3]='\0';

    if(pre_Norm[0]=='1'){
        out_exponent_int=+1;
    }
    post_Norm=nomalize(pre_Norm,FRACTION_WIDTH+3);


    free(MxFraMult);
    free(MyFraMult);
}


char * MbyMMulttplier(char Mx[], char My[], int m_size){

    
    int Mx_Int=binary2INT(Mx,m_size);
    int My_Int=binary2INT(My,m_size);
    int mult_result_int=Mx_Int*My_Int;
    printf("Mx_Int: %d, My_Int: %d\n", Mx_Int, My_Int);
    char * out_arr=INT2binary(mult_result_int,m_size*2);
    return out_arr;
}

//just shifting 1 position to the right
char * nomalize(char inArr[], int size){
    int i;
    char *ShiftResult = (char *) malloc(sizeof (char) *(size-1));
    ShiftResult[size-2]='\0';
    if(inArr[0]=='1'){
        for (i=0;i<size-2;i++){
            ShiftResult[i]=inArr[i+1];
        }
    }else{
        for (i=0;i<size-2;i++){
            ShiftResult[i]=inArr[i+2];
        }
    }


    return ShiftResult;
}